
package com.kanjian.music.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.database.Cursor;

import com.kanjian.music.config.Config;
import com.kanjian.music.constants.PlayerConstants;
import com.kanjian.music.constants.SharedPreferenceKeyConstants;
import com.kanjian.music.database.DatabaseManager;
import com.kanjian.music.database.DownloadListDao;
import com.kanjian.music.database.MusicDao;
import com.kanjian.music.entity.Music;
import com.kanjian.music.service.PlayerService;

import de.greenrobot.dao.WhereCondition.StringCondition;

/**
 * 播放器辅助工具类 维护播放列表
 * 
 * @author xuyanjun@kanjian.com
 */
public class PlayerUtil {

    // 播放器显示播放列表
    public static ArrayList<Music> playerList = new ArrayList<Music>();

    // 实际播放列表(随机播放、单曲循环与显示播放列表不同)
    private static ArrayList<Music> realPlayList = new ArrayList<Music>();

    private static int currentPlayIndex = 0;

    // 播放器类型_歌曲
    public static final int PLAYERTYPE_MUSICLIST = 0;

    // 播放器类型_电台
    public static final int PLAYERTYPE_RADIO = 1;

    // 当前播放器类型
    public static int mPlayerType = PLAYERTYPE_MUSICLIST;

    // 当前电台类型
    public static int mCurrentRadioType = -1;

    // 是否边听边存
    public static boolean isDownloadOnPlaying() {
        return Config.IS_DOWNLOAD_WITH_PLAY;
    }

    public static void paddingLocalMusicList() {
        Config.CURRENT_PLAY_MODE = SharedPreferenceUtil.getInt(
                SharedPreferenceKeyConstants.SPKEY_PLAY_MODE, PlayerConstants.PLAY_MODE_LIST_CYCLE);

        String sql = "SELECT * FROM download_list AS d " + "LEFT JOIN music AS m "
                + "ON d.music_id = m.music_id " + "GROUP BY d.music_id "
                + "HAVING d.download_status=0 AND d.download_type=0 "
                + "ORDER BY d.display_order DESC";
        Cursor cursor = DatabaseManager.session.getDatabase().rawQuery(sql, null);
        List<Music> localList = null;

        if (cursor != null && cursor.moveToFirst()) {
            int musicIdIndex = cursor.getColumnIndex(MusicDao.Properties.MusicId.columnName);
            int downloadTypeIndex = cursor
                    .getColumnIndex(DownloadListDao.Properties.DownloadType.columnName);
            int downloadStatusIndex = cursor
                    .getColumnIndex(DownloadListDao.Properties.DownloadStatus.columnName);
            int localPathIndex = cursor
                    .getColumnIndex(DownloadListDao.Properties.LocalPath.columnName);
            int isFavIndex = cursor.getColumnIndex(MusicDao.Properties.IsFav.columnName);
            int userPicIndex = cursor.getColumnIndex(MusicDao.Properties.UserPic.columnName);
            int userIdIndex = cursor.getColumnIndex(MusicDao.Properties.UserId.columnName);
            int musicUrlIndex = cursor.getColumnIndex(MusicDao.Properties.MusicUrl.columnName);
            int musicianLocationIndex = cursor
                    .getColumnIndex(MusicDao.Properties.MusicianLocation.columnName);
            int playTimeIndex = cursor.getColumnIndex(MusicDao.Properties.PlayTime.columnName);
            int userNameIndex = cursor.getColumnIndex(MusicDao.Properties.UserName.columnName);
            int musicNameIndex = cursor.getColumnIndex(MusicDao.Properties.MusicName.columnName);

            Music music;
            localList = new ArrayList<Music>(cursor.getCount());
            do {
                music = new Music();
                music.setMusicId(cursor.getLong(musicIdIndex));
                music.mDownloadType = cursor.getInt(downloadTypeIndex);
                music.mDownloadStatus = cursor.getInt(downloadStatusIndex);
                music.mLocalPath = cursor.getString(localPathIndex);
                music.setIsFav(cursor.getInt(isFavIndex));
                music.setUserPic(cursor.getString(userPicIndex));
                music.setUserId(cursor.getInt(userIdIndex));
                music.setMusicUrl(cursor.getString(musicUrlIndex));
                music.setMusicianLocation(cursor.getString(musicianLocationIndex));
                music.setPlayTime(cursor.getInt(playTimeIndex));
                music.setUserName(cursor.getString(userNameIndex));
                music.setUserId(cursor.getInt(userIdIndex));
                music.setMusicName(cursor.getString(musicNameIndex));
                localList.add(music);

            } while (cursor.moveToNext());
        }
        cursor.close();
        
        if (localList != null && localList.size() > 0) {
        
            playerList.addAll(localList);
            realPlayList.addAll(localList);
            if (Config.CURRENT_PLAY_MODE == PlayerConstants.PLAY_MODE_RANDOM) {
                shufflePlayList();
            }
        
        }
    }

    // 获取当前正在播放的歌曲
    public static Music getCurrentPlayingMusic() {
        if (realPlayList != null && realPlayList.size() > 0) {
            if (realPlayList.size() >= currentPlayIndex + 1) {
                return realPlayList.get(currentPlayIndex);
            } else {
                return realPlayList.get(0);
            }
        } else {
            return null;
        }
    }

    // 把playindex移动到下一首
    public static void next() {
        if (realPlayList != null && realPlayList.size() > 0
                && currentPlayIndex + 1 >= realPlayList.size()) {
            currentPlayIndex = 0;
        } else {
            currentPlayIndex++;
        }
    }

    // 把playindex移动到上一首
    public static void pre() {
        if (realPlayList != null && realPlayList.size() > 0 && currentPlayIndex - 1 < 0) {
            currentPlayIndex = realPlayList.size() - 1;
        } else {
            currentPlayIndex--;
        }
    }

    public static void setPlayerList(ArrayList<Music> musicList) {
        playerList = musicList;
        if (Config.CURRENT_PLAY_MODE == PlayerConstants.PLAY_MODE_RANDOM) {
            shufflePlayList();
        }
    }

    // 打乱播放列表
    public static void shufflePlayList() {
        ArrayList<Music> tempList = new ArrayList<Music>(playerList);
        Collections.shuffle(playerList);
        Collections.copy(realPlayList, playerList);
        Collections.copy(playerList, tempList);
        tempList.clear();
        tempList = null;
    }

    // 添加一首歌曲到播放列表并保存到本地数据库
    public static void addMusic(Music music) {
        MusicDao musicDao = DatabaseManager.session.getMusicDao();
        musicDao.insertOrReplace(music);
        playerList.add(music);
        realPlayList.add(music);
        shufflePlayList();
    }

    public static void addMusicList(ArrayList<Music> musicList) {
        MusicDao musicDao = DatabaseManager.session.getMusicDao();
        musicDao.insertOrReplaceInTx(musicList);
        playerList.addAll(musicList);
        realPlayList.addAll(musicList);
        shufflePlayList();
    }

    public static void addMusicListThenPlay(ArrayList<Music> musicList, PlayerService service) {
        addMusicList(musicList);
        if (musicList != null && musicList.size() > 0) {
            currentPlayIndex = findMusicIndex(musicList.get(0).getMusicId());
            if (service != null) {
                mPlayerType = PLAYERTYPE_MUSICLIST;
                service.play();
            }
        }
    }

    /**
     * 向播放器添加临时列表 比如：电台
     * 
     * @param musicList
     * @param service
     */
    public static void addTempleMusicListThenPlay(ArrayList<Music> musicList, PlayerService service) {
        if (musicList != null && musicList.size() > 0) {
            playerList.clear();
            playerList.addAll(musicList);
            realPlayList.clear();
            realPlayList.addAll(musicList);
            shufflePlayList();
            currentPlayIndex = 0;
            if (service != null) {
                mPlayerType = PLAYERTYPE_RADIO;
                setPlayMode(PlayerConstants.PLAY_MODE_LIST_CYCLE);
                service.play();
            }
        }
    }

    /**
     * 根据musicID找到当前播放列表中的index
     * 
     * @param musicId
     * @return -1 not found
     */
    private static int findMusicIndex(long musicId) {
        int size = realPlayList.size();
        for (int i = 0; i < size; i++) {
            if (realPlayList.get(i).getMusicId() == musicId) {
                return i;
            }
        }
        return -1;
    }

    public static void addMusicThenPlay(Music music, PlayerService service) {
        addMusic(music);
        currentPlayIndex = findMusicIndex(music.getMusicId());
        if (service != null) {
            mPlayerType = PLAYERTYPE_MUSICLIST;
            service.play();
        }
    }

    public static String getPlayModeStr() {
        switch (Config.CURRENT_PLAY_MODE) {
            case PlayerConstants.PLAY_MODE_RANDOM:
                return "随机播放";
            case PlayerConstants.PLAY_MODE_LIST_CYCLE:
                return "循序播放";
            case PlayerConstants.PLAY_MODE_SINGLE_CYCLE:
                return "单曲循环";
            default:
                return "循序播放";
        }
    }

    private static void setPlayMode(int playMode) {
        if (realPlayList != null && playerList != null) {
            switch (playMode) {
                case PlayerConstants.PLAY_MODE_RANDOM:
                    realPlayList.clear();
                    realPlayList = new ArrayList<Music>(playerList);
                    shufflePlayList();
                    break;
                case PlayerConstants.PLAY_MODE_LIST_CYCLE:
                    realPlayList.clear();
                    realPlayList = new ArrayList<Music>(playerList);
                    break;
                case PlayerConstants.PLAY_MODE_SINGLE_CYCLE:
                    realPlayList.clear();
                    realPlayList = new ArrayList<Music>(playerList);
                    break;
                default:
                    break;
            }
        }
    }

    public static String togglePlayMode() {
        long playingMusicId = 0;
        Config.CURRENT_PLAY_MODE++;
        if (Config.CURRENT_PLAY_MODE > PlayerConstants.PLAY_MODE_RANDOM) {
            Config.CURRENT_PLAY_MODE = PlayerConstants.PLAY_MODE_LIST_CYCLE;
        }
        SharedPreferenceUtil.put(SharedPreferenceKeyConstants.SPKEY_PLAY_MODE,
                Config.CURRENT_PLAY_MODE);

        if (realPlayList != null && playerList != null) {
            playingMusicId = getCurrentPlayingMusic().getMusicId();
            switch (Config.CURRENT_PLAY_MODE) {
                case PlayerConstants.PLAY_MODE_RANDOM:
                    realPlayList.clear();
                    realPlayList = new ArrayList<Music>(playerList);
                    shufflePlayList();
                    break;
                case PlayerConstants.PLAY_MODE_LIST_CYCLE:
                    realPlayList.clear();
                    realPlayList = new ArrayList<Music>(playerList);
                    break;
                case PlayerConstants.PLAY_MODE_SINGLE_CYCLE:
                    realPlayList.clear();
                    realPlayList = new ArrayList<Music>(playerList);
                    break;
                default:
                    break;
            }
        }

        currentPlayIndex = findMusicIndex(playingMusicId);

        return getPlayModeStr();
    }

    public static String toTime(int time) {
        int minute = time / 60;
        int second = time % 60;
        return String.format("%02d:%02d", minute, second);
    }

    public static void removeCurrentMusic() {
        playerList.remove(currentPlayIndex);
        realPlayList.remove(currentPlayIndex);
    }

}
